<template>
  <div class="display-list">
    <template v-if="fileGroups.length > 0">
      <div v-bind="containerProps" class="virtual-container">
        <div v-bind="wrapperProps">
          <div v-for="group in list" :key="group.data.date">
            <DateGroup :date="group.data.date">
              <div class="file-list">
                <FileListHeader />
                <FileListItem
                  v-for="file in group.data.files"
                  :key="file.id"
                  :file="file"
                  @file-click="onFileClick"
                  @download="onDownload"
                  @delete="onDelete"
                />
              </div>
            </DateGroup>
          </div>
        </div>
      </div>
    </template>

    <EmptyState v-else />
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useVirtualList } from '@vueuse/core'
import DateGroup from './DateGroup.vue'
import FileListHeader from './FileListHeader.vue'
import FileListItem from './FileListItem.vue'
import EmptyState from './EmptyState.vue'

const props = defineProps({
  files: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['file-click', 'download', 'delete'])

// 预处理文件按日期分组
const fileGroups = computed(() => {
  const groups = {}

  if (props.files) {
    props.files.forEach((file) => {
      const dateKey = new Date(file.date).toISOString().split('T')[0]
      if (!groups[dateKey]) {
        groups[dateKey] = {
          date: dateKey,
          files: []
        }
      }
      groups[dateKey].files.push(file)
    })

    // 转换为数组并排序
    return Object.values(groups).sort(
      (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
    )
  }

  return []
})

// 使用虚拟列表
const { list, containerProps, wrapperProps } = useVirtualList(fileGroups, {
  itemHeight: (idx) => {
    const group = fileGroups.value[idx]
    if (!group) return 0

    // 日期头部高度 + 列表头部高度 + 每个文件项高度 * 文件数量
    const headerHeight = 40
    const listHeaderHeight = 40
    const fileItemHeight = 56

    return headerHeight + listHeaderHeight + group.files.length * fileItemHeight
  },
  overscan: 5 // 预渲染的额外项目数量
})

// 事件处理
const onFileClick = (file: any): void => {
  emit('file-click', file)
}

const onDownload = (file: any): void => {
  emit('download', file)
}

const onDelete = (file: any): void => {
  emit('delete', file)
}
</script>

<style scoped>
.display-list {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0; /* 重要：允许内容收缩 */
}

.virtual-container {
  flex: 1;
  min-height: 0; /* 重要：允许内容收缩 */
  overflow-y: auto;
}

.file-list {
  background-color: var(--theme-bg-secondary);
  border-radius: 8px;
  border: 1px solid var(--theme-border-light);
  overflow: hidden;
}
</style>
